package com.system.mqConsumer;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.time.Duration;
import java.util.Arrays;
import java.util.Properties;

public class DelayedQueue {
    private final KafkaConsumer<String, String> consumer;
    private final KafkaProducer<String, String> producer;
    private final String topic;

    public DelayedQueue(String servers, String groupId, String topic) {
        Properties consumerProps = new Properties();
        consumerProps.put("bootstrap.servers", servers);
        consumerProps.put("group.id", groupId);
        consumerProps.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        consumerProps.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        this.consumer = new KafkaConsumer<>(consumerProps);
        this.consumer.subscribe(Arrays.asList(topic));

        Properties producerProps = new Properties();
        producerProps.put("bootstrap.servers", servers);
        producerProps.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        producerProps.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

        this.producer = new KafkaProducer<>(producerProps);
        this.topic = topic;
    }

    public void run(long delayMillis) throws Exception {
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));

            for (ConsumerRecord<String, String> record : records) {
                long elapsed = System.currentTimeMillis() - record.timestamp();

                if (elapsed < delayMillis) {
                    // 如果消息未达到延时期限，则重新发布到主题中，并增加延时时间
                    producer.send(new ProducerRecord<>(topic, record.partition(), record.timestamp(), record.key(), record.value(), record.headers()));
                    Thread.sleep(delayMillis - elapsed);
                } else {
                    // 处理消息
                    process(record);
                }
            }
        }
    }

    private void process(ConsumerRecord<String, String> record) {
        // 在这里处理消息，例如打印消息内容：
        System.out.println("Processing message: " + record.value());
    }
}